<?php

namespace Esseak\FetchPackage\Console;

use Exception;
use Illuminate\Console\Command;
use GuzzleHttp\Client;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;

class FetchDatasCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fetch:getVideos {--page=0} {--pageSize=10}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '获取数据  {--page=0} {--pageSize=10}';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $page = $this->option('page');
        $pageSize = $this->option('pageSize');
        $client = new Client;
        //https://api.apiopen.top/api/getHaoKanVideo?page=0&size=10
        $res = $client->request('GET', "https://api.apiopen.top/api/getHaoKanVideo?page={$page}&size={$pageSize}");
        $body = json_decode($res->getBody()->getContents(),true);
        if($body && $body['code'] == 200){
            $list = collect($body['result']['list'])->map(function($item){
                $item['source_id'] = $item['id'];
                $item['created_at'] = Carbon::now();
                $item['updated_at'] = Carbon::now();
                unset($item['id']);
                return $item;
            })->toArray();

            try{
                DB::transaction(function() use ($list){
                    DB::table('videos')->insert($list);
                });
                Log::info('FetchDatas',['success at '. Carbon::now()]);

            }catch(Exception $e){
                Log::info('FetchDatas',['fail at '. Carbon::now()]);
            }
            
        }else{
            Log::info('FetchDatas',['fail http at '. Carbon::now()]);
        }
        return 0;
    }
}
